package com.bitcat.firstapp.demo.musicdemo

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bitcat.firstapp.R
import com.bitcat.firstapp.databinding.ActivityMusicListBinding
import com.permissionx.guolindev.PermissionX
import es.dmoral.toasty.Toasty
import kotlin.concurrent.thread

class MusicListActivity : AppCompatActivity() {

    private val binding: ActivityMusicListBinding by lazy {
        ActivityMusicListBinding.inflate(layoutInflater)
    }

    private val musicAdapter = MusicAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        //ListView

        binding.rvMusic.adapter = musicAdapter
        musicAdapter.setOnItemClickListener(object :MusicAdapter.OnItemClickListener{
            override fun onItemClick(musicInfo: MusicInfo) {
                val intent = Intent(this@MusicListActivity, MusicDetailActivity::class.java)
                intent.putExtra("music",musicInfo)
                startActivity(intent)
            }
        })
        requestPermission()
    }


    fun requestPermission(){
        val permission = if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.TIRAMISU)
            Manifest.permission.READ_MEDIA_AUDIO
        else
            Manifest.permission.READ_EXTERNAL_STORAGE

        PermissionX.init(this)
            .permissions(permission)
            //解释为什么需要权限，跳转到设置页面的弹窗
            .request{ allGranted, grantedList, deniedList ->
                if (allGranted){
                    loadMusicList()
                }else{
                    Toasty.error(this,"权限申请失败").show()
                }
            }

    }

    private fun loadMusicList() {
        thread {
            val musicList = queryMusicList()
            runOnUiThread {
                musicAdapter.updateMusicList(musicList)
            }
        }
    }

    private fun queryMusicList(): List<MusicInfo> {
        //创建一个List
        val musicList = mutableListOf<MusicInfo>()

        //查询条件：音乐时长大于1分钟
        val selection = "${MediaStore.Audio.Media.DURATION} > ?"
        val selectionArgs = arrayOf("60000")

        contentResolver.query(
            MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            arrayOf(
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.DURATION,
                MediaStore.Audio.Media.SIZE,
                MediaStore.Audio.Media.DATA
            ),
            selection,
            selectionArgs,
            null
        )?.use { cusor->
            val idIndex = cusor.getColumnIndex(MediaStore.Audio.Media._ID)
            val titleIndex = cusor.getColumnIndex(MediaStore.Audio.Media.TITLE)
            val artistIndex = cusor.getColumnIndex(MediaStore.Audio.Media.ARTIST)
            val durationIndex = cusor.getColumnIndex(MediaStore.Audio.Media.DURATION)
            val sizeIndex = cusor.getColumnIndex(MediaStore.Audio.Media.SIZE)
            val pathIndex = cusor.getColumnIndex(MediaStore.Audio.Media.DATA)
            while (cusor.moveToNext()){
                val id = cusor.getLong(idIndex)
                val title = cusor.getString(titleIndex)
                val artist = cusor.getString(artistIndex)
                val duration = cusor.getLong(durationIndex)
                val size = cusor.getLong(sizeIndex)
                val path = cusor.getString(pathIndex)

                val musicItem = MusicInfo(id, title, artist, duration, size, path)
                musicList.add(musicItem)
            }

        }
        //播放在线音乐
        val item = MusicInfo(
            id = 999,
            title = "真的爱你",
            artist = "beyond",
            duration = 275000,
            size = 0,
//            path = "http://10.0.2.2:8081/zhendeaini.mp3"
            path = "http://192.168.1.4:8081/zhendeaini.mp3"
        )

        musicList.add(0,item)
        return musicList
    }
}